package utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    private static Connection connection = null;

    public static Connection getConnection() {
        if (connection != null) {
            return connection;
        } else {

            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            String path = systemClassLoader.getResource("").getPath();
            System.out.println(path);

            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(path + "jdbc.properties");
                Properties properties = new Properties();
                properties.load(fileInputStream);

                String driver = properties.getProperty("driverName");
                String user = properties.getProperty("user");
                String password = properties.getProperty("password");
                String url = properties.getProperty("url");

                Class.forName(driver);
                connection = DriverManager.getConnection(url, user, password);
            } catch (IOException | SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            return connection;
        }
    }

    public static void closeConnection(){
        if (connection == null) {
            return;
        }
        else {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
